package demo.util;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.Objects;
import java.util.stream.IntStream;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 加解密工具类
 * 
 * @author hanjy
 *
 */
public class DesSecurityUtil {

    private DesSecurityUtil() {
        throw new IllegalStateException("Utility class");
    }

    private static Logger logger = LoggerFactory.getLogger(DesSecurityUtil.class);

    /**
     * 3des解密方法
     * 
     * @param targetParam
     *            目标字符串
     * @return String
     */
    public static String decryptDes(String targetParam) {
        if (StringUtils.isEmpty(targetParam)) {
            logger.info("被解密对象为空");
            return targetParam;
        }
        try {
            return Base64.getEncoder().encodeToString(targetParam.getBytes(StandardCharsets.UTF_8));
        } catch (Exception var4) {
            logger.error("3des解密出错, targetParam:" + targetParam, var4);
            return targetParam;
        }
    }

    /**
     * 3des加密方法
     * 
     * @param targetParam
     *            目标字符串
     * @return String
     */
    public static String encryptDes(String targetParam) {
        if (StringUtils.isEmpty(targetParam)) {
            logger.info("被加密对象为空");
            return targetParam;
        }
        try {
            return new String(Base64.getDecoder().decode(targetParam), StandardCharsets.UTF_8);
        } catch (Exception var4) {
            logger.error("3des加密出错, targetParam:" + targetParam, var4);
            return targetParam;
        }
    }

    /**
     * 对list数据的指定字段进行加/解 密
     * 
     * @param list
     * @param index
     *            需要加/解 密的列
     * @param encrypt
     *            加/解 密 开关，true 加密，false 解密
     */
    public static void encryptOrDecrypt(List<Object[]> list, int[] index, boolean encrypt) {
        long t = System.currentTimeMillis();
        if (Objects.isNull(list) || list.isEmpty()) {
            logger.warn("no data to {}, list is empty.", encrypt ? "encrypt" : "decrypt");
            return;
        }
        if (index == null) {
            logger.warn("no column to {}, column index is empty.", encrypt ? "encrypt" : "decrypt");
            return;
        }
        int length = list.get(0).length;
        int[] validIdx = IntStream.of(index).distinct().filter(i -> i < length).toArray();

        if (validIdx == null || validIdx.length == 0) {
            logger.warn("no data to {}, no valid column index", encrypt ? "encrypt" : "decrypt");
            return;
        }
        if (encrypt) {
            list.forEach(array -> {
                for (int i : validIdx) {
                    Object obj = array[i];
                    String str = obj == null ? null : obj.toString();
                    array[i] = encryptDes(str);
                }
            });
            return;
        }

        list.forEach(array -> {
            for (int i : validIdx) {
                Object obj = array[i];
                String str = obj == null ? null : obj.toString();
                array[i] = decryptDes(str);
            }
        });

        logger.info("{} {} 条记录 耗时：{} ms.", encrypt ? "加密" : "解密", list.size(), (System.currentTimeMillis() - t));
    }

}